package live.hotel.dao.job;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;

import live.common.Format;
import live.common.MemCached;
import live.common.Page;
import live.hotel.entity.Search;
import live.hotel.service.SearchHotelPrice;


public class HotelBaseQuery implements Runnable {
	private String code;
	private Search search=null;
	private SearchHotelPrice hotel = null;
	private List list = null;
	final static String format="yyyy-MM-dd";
	final Page page = new Page(1,20,0,20);
	private MemCached cached = MemCached.getInstance();
	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}
	
	public  HotelBaseQuery(String code) {
		// TODO Auto-generated constructor stub
		hotel=new SearchHotelPrice();
		this.setCode(code);
	}
	public void run() {
		// TODO Auto-generated method stub
		synchronized (this) {
			try {
				list = hotel.getHotelPriceBase(page, returnSearch());
				JSONArray obj =  JSONArray.fromObject(list);
				if(cached.get(code)==null){
					cached.add(code, obj);
				}else{
					cached.replace(code, obj);
				}
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				hotel=null;
				list=null;
				search=null;
			}
		}
	}
	
	private Search returnSearch(){
		search = new Search();
		search.setCityCode(getCode());
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.DATE, +1);
		search.setCheckInDate(Format.getInstance().dateFormatString(calendar.getTime(), format));
		calendar.setTime(new Date());
		calendar.add(Calendar.DATE, +2);
		search.setCheckOutDate(Format.getInstance().dateFormatString(calendar.getTime(), format));
		return search; 
	}
}
